//
//  TRFriendViewController.m
//  TLBS
//
//  Created by tarena on 14-3-28.
//  Copyright (c) 2014年 tarena. All rights reserved.
//

#import "TRFriendViewController.h"
#import "UserInfoViewController.h"
#import "TRAppDelegate.h"
#import "TRWeiboUtils.h"
#import "WeiboPaser.h"
#import "TRMyRequest.h"
#import "UserInfoCell.h"
@interface TRFriendViewController ()
@property (nonatomic, weak)TRAppDelegate *app;
@property (nonatomic, copy)NSString *listID;
@property (nonatomic, strong)NSMutableArray *requests;
@property (nonatomic, strong)NSMutableArray *users;
@property (nonatomic, strong)TRWeiboUtils *weiboUtils;
@end

@implementation TRFriendViewController
- (IBAction)addFriend:(id)sender {
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"添加好友" message:@"请输入好友的name" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Sure", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {//添加好友
        NSString* userName = [alertView textFieldAtIndex:0].text;
        
        TRMyRequest *request = [[TRMyRequest alloc]init];
        
        [self.requests addObject:request];
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"json" forKey:@"format"];
        
        [params setObject:userName forKey:@"names"];
        [params setObject:self.listID forKey:@"listid"];
        [request requestWithParams:params apiName:@"list/add_to_list" httpMethod:@"POST" :^(NSString *jsonString) {
            NSLog(@"添加好友：%@",jsonString);
            [self getFriendList];
        }];
        
    }
}


- (void)viewDidLoad
{
    self.weiboUtils = [[TRWeiboUtils alloc]init];
    self.requests = [NSMutableArray array];
    [super viewDidLoad];
    self.app = [UIApplication sharedApplication].delegate;
     self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};

    
    
    //查询所有名单
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"json" forKey:@"format"];

    TRMyRequest *request = [[TRMyRequest alloc]init];

    [self.requests addObject:request];
    [request requestWithParams:params apiName:@"list/get_list" httpMethod:@"POST" :^(NSString *jsonString) {
        [self.requests removeObject:request];
        NSArray *lists = [WeiboPaser getListByJsonString:jsonString];
        if (lists.count == 0) {//没有名单 需要创建一个名单
            
            [self createList];
            
        }else{
            NSDictionary *listDic = lists[0];
            self.listID = [listDic objectForKey:@"listid"];
            //得到名单id之后获得此名单下面的所有的好友列表
            [self getFriendList];
        }
     
    }];
}
//查询名单下的好友列表
-(void)getFriendList{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"json" forKey:@"format"];
    [params setObject:self.listID forKey:@"listid"];
    [params setObject:@"0" forKey:@"pageflag"];
    
    TRMyRequest *request = [[TRMyRequest alloc]init];
    [self.requests addObject:request];
    [request requestWithParams:params apiName:@"list/listusers" httpMethod:@"POST" :^(NSString *jsonString) {
        self.users = [[WeiboPaser paseAllUserByJsonString:jsonString] mutableCopy];
        [self.tableView reloadData];
    }];
}

-(void)createList{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"json" forKey:@"format"];
    [params setObject:@"微身边专用 误删" forKey:@"description"];
    [params setObject:@"我的名单a" forKey:@"name"];
   
    [params setObject:@"TLBS" forKey:@"tag"];
    [params setObject:@"1" forKey:@"access"];
//    以前的写法
//    [self.app.weiboApi requestWithParams:params  apiName:@"list/create" httpMethod:@"POST" delegate:self];
//    现在的写法
    TRMyRequest *request = [[TRMyRequest alloc]init];
    [self.requests addObject:request];
    [request requestWithParams:params apiName:@"list/create" httpMethod:@"POST" :^(NSString *jsonString) {
        self.listID = [WeiboPaser getListIDByJsonString:jsonString];
        NSLog(@"%@",self.listID);
        [self.requests removeObject:request];
    }];
}

-(void)viewDidAppear:(BOOL)animated{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.app.weiboApi loginWithDelegate:self andRootController:self];
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return self.users.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UserInfoCell *cell = (UserInfoCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    cell.userInfo = self.users[indexPath.row];
    
    return cell;
}
 


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
     //删除好友
        UserInfo *deleteUser = self.users[indexPath.row];
        
        [self.weiboUtils deleteFriend:deleteUser withListID:self.listID];
        [self.users removeObject:deleteUser];
    
         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


//选中某一行的时候跳转到查看信息的页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UserInfoViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"UserInfoViewController"];
    UserInfo *user = self.users[indexPath.row];
    vc.userName = user.name;
    [self.navigationController pushViewController:vc animated:YES];
    
}





@end
